package com.kstudio.ksnapshot.kimage;

import java.util.ArrayList;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.kstudio.ksnapshot.KUtil;
import com.kstudio.ksnapshot.R;

public class KImageAdapter extends ArrayAdapter<KImageFileData> {
    KUtil log = new KUtil("KImageActivity");
    public static final int Null_Image = R.drawable.kimage_temp;

    private final Context context;
    private int columWidth;
    private int columHeight;

    public KImageAdapter(Context context, ArrayList<KImageFileData> objects, int columWidth, int columHeight) {
        super(context, 0, objects);

        this.context = context;
        this.columWidth = columWidth;
        this.columHeight = columHeight;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView view = (ImageView) convertView;
        KImageViewWrapper viewWrapper;

        if(view == null) {
            view = new ImageView(context);
            view.setLayoutParams(new GridView.LayoutParams(columWidth,columHeight));
            view.setAdjustViewBounds(false);
            view.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            view.setBackgroundResource(R.drawable.kimage_icon_bg);
            viewWrapper = new KImageViewWrapper(view);
            view.setTag(viewWrapper);
        } else {
            viewWrapper = (KImageViewWrapper)view.getTag();
        }

        final KImageFileData data = (KImageFileData) this.getItem(position);
        if(data != null) {
            if(data.getBitmap() != null) {
                viewWrapper.getImageView().setImageBitmap(data.getBitmap());
            } else {
                viewWrapper.getImageView().setImageResource(Null_Image);
            }
        }

        return view;
    }

    private class KImageViewWrapper {
        private ImageView Base;

        public KImageViewWrapper(View base) {
            Base = (ImageView) base;
        }

        public ImageView getImageView() {
            return Base;
        }
    }
}
